package common.WxProgram;

import com.alibaba.fastjson.JSONObject;
import com.xz.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 调用http接口post-json格式请求
 */
@Component
public class HttpClientUtil {

    // 接口调用结果CODE
    public static final String SEND_POST_CODE = "responseCode";

    public static final String SEND_POST_MSG = "responseMsg";

    // 接口调用成功
    public static final String SEND_POST_SUCCESS = "000000";

    //接口调用失败
    public static final String SEND_POST_FAIL = "999999";


    private static URL createURL(String url, Map<String, Object> param) throws MalformedURLException {
        if (param == null || param.size() == 0){
            return new URL(url);
        }
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        for (String key : param.keySet()) {
            sb.append(key);
            sb.append("=");
            sb.append(encode(String.valueOf( param.get(key))));
            sb.append("&");
        }
        return new URL(sb.substring(0, sb.length() - 1));
    }

    public static String encode(String text) {
        try {
            return URLEncoder.encode(text, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的URL 例如：http://localhost:8080/demo/login
     * @param param 请求参数 例：{ "userName":"admin", "password":"123456" }
     * @return  所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, Object> param) {
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = createURL(url, param);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.connect();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }


    /**
     * 调用接口通用方法(不携带cookie)
     * @param url 请求地址
     * @param jsonObject 请求参数
     * @return
     */
    public JSONObject unify(String url,JSONObject jsonObject) {
        JSONObject result = null;
        CloseableHttpResponse response = null;
        try {
            // 创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            // 请求超时设置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(50000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(50000).build();
            httpPost.setConfig(requestConfig);
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.custom().build();
            //装填参数
            if(jsonObject != null) {
                System.out.println(jsonObject.toString());
                StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json"));
                //设置参数到请求对象中
                httpPost.setEntity(s);
            }
            //执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            result =  JSONObject.parseObject(EntityUtils.toString(entity, "utf-8"));
        } catch(Exception e) {
            result.put(SEND_POST_CODE,SEND_POST_FAIL);
            result.put(SEND_POST_MSG,e.toString());
        } finally {
            if(response != null) {
                //释放链接
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

    // post请求获取短租隐私协议或者服务协议
    public static String sendHttpPost(String url, JSONObject jsonObject) throws Exception {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);

        //设置header信息
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;

    }


    /**
     * 资产系统修改车辆属性
     * @param url
     * @param jsonObject
     * @return
     */
    public JSONObject unifyAttribute(String url,JSONObject jsonObject) {
        JSONObject result = null;
        CloseableHttpResponse response = null;
        try {
            // 创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            // 请求超时设置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.custom().build();
            //装填参数
            if(jsonObject != null) {
                StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json"));
                //设置参数到请求对象中
                httpPost.setEntity(s);
            }
            //执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            result =  JSONObject.parseObject(EntityUtils.toString(entity, "utf-8"));
        } catch(Exception e) {
            result.put(SEND_POST_CODE,SEND_POST_FAIL);
            result.put(SEND_POST_MSG,e.toString());
        } finally {
            if(response != null) {
                //释放链接
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return result;
        }
    }



    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL 例如：http://localhost:8080/demo/login
     * @param param 请求参数 例：{ "userName":"admin", "password":"123456" }
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, Map<String, Object> param) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = createURL(url, param);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.connect();
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }
    /**
     * 向指定URL发送GET方法的请求--Cookie
     *
     * @param url   发送请求的URL 例如：http://localhost:8080/demo/login
     * @param param 请求参数 例：{ "userName":"admin", "password":"123456" }
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGetCookie(String url, Map<String, Object> param,String cookie) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = createURL(url, param);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Cookie", cookie);
            conn.connect();
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }

    public static String post(String url, JSONObject jsonObject, String token) throws Exception {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);
        // 设置请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(3000) // 设置Socket超时时间为3秒
                .setConnectTimeout(3000) // 设置连接超时时间为3秒
                .setConnectionRequestTimeout(3000) // 设置请求超时时间为3秒
                .build();
        httpPost.setConfig(requestConfig);
        //设置header信息
      //  httpPost.setHeader("token",token);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        System.out.println(body);
        return body;

    }


    public static void main(String[] args) throws Exception{

        Map<String,Object> map=new HashMap<>();
        map.put("action","merchant.web.order.list");
        map.put("token","f0b49cbab9294db48c7492bb4f5a4335");
        map.put("siteIds",new ArrayList<>());
        map.put("pageSize",20);
        map.put("pageIndex",1);
        map.put("status",40);

        post("https://rentpms.hellobike.com/api?merchant.web.order.list",JSONObject.parseObject(JSONObject.toJSONString(map)),"");
    }
}
